package org.yyds;

import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;

import java.io.File;
import java.util.Arrays;

public class ConfigLoader {

    private static final String CONFIG_NAME = "config.properties";

    public static Configuration getConfig() {
        Configurations configs = new Configurations();
        Configuration config = null;

        // 尝试从当前运行的Jar包所在目录加载配置文件
        File jarPath = new File(ConfigLoader.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        File externalConfigFile = new File(jarPath.getParentFile(), CONFIG_NAME);

        System.out.println("加载配置文件：" + externalConfigFile);

        // 如果存在外部的配置文件，则使用外部的配置文件
        if (externalConfigFile.exists()) {
            try {
                config = configs.properties(externalConfigFile);
            } catch (ConfigurationException e) {
                e.printStackTrace();
                System.err.println(e.getMessage());
                System.exit(0);
            }
        } else {
            String format = String.format("%s 目录下不存在 %s 配置文件", externalConfigFile.getParent(), CONFIG_NAME);
            System.err.println(format);
            System.exit(0);
        }
        return config;
    }

    public static void main(String[] args) {
        Configuration config = ConfigLoader.getConfig();

        int port = config.getInt("sftpserver.port");
        String sftpserverUser = config.getString("sftpserver.username");
        String sftpserverPassword = config.getString("sftpserver.password");
        String userHomeDir = config.getString("sftpserver.userhomedir");

        System.out.println(port);
        System.out.println(sftpserverUser);
        System.out.println(sftpserverPassword);

        System.out.println(userHomeDir);
    }
}
